//! @Author: DengLibin 榆霖
//! @Date:  2022-07-05 13:49:58
//! @Des&cription: 



use std::{cell::RefCell, collections::HashMap};

use actix_web::{
    HttpResponse, Scope, web::{Data, self}, post,get
};

use bcrypt::{hash, DEFAULT_COST};
use common::pojo::ResData;
use async_dao::{entity::user::User, pojo::DbParam};
use service::async_user_service;

/// @Author: DengLibin 榆霖
/// @Date:  2022-04-21 11:33:&01
/// @Description: 路由配置
pub fn route() -> Scope{
    info!("async_user_controller配置路由");
    let sys_scope = web::scope("/async_user");
    sys_scope
    .service(insert)
    .service(get_page)
}



/// @Author: DengLibin 榆霖
/// @Date:  2022-07-06 11:17:13
/// @Description: 添加
#[post("/insert")]
async fn insert(
    id_generator: Data<RefCell<common::utils::IdGenerator>>, //id生成器
    async_mysql_conn_pool: Data<mysql_async::Pool>, //连接池，全局参数传过来
    user: web::Json<User>
    
    ) -> HttpResponse {
     //获取连接池
    let p = (*(async_mysql_conn_pool)).clone();
    let generator = id_generator;
    let mut u = user.to_owned();
    u.id = generator.borrow_mut().next_id();
    u.passwords = hash(u.passwords, DEFAULT_COST).unwrap();
    u.create_by = -1;
    u.update_by = -1;
    u.deleted = false;
    let param = async_dao::pojo::UserParam { user: u, pool: p};
    let r = async_user_service::insert(&param).await;    
    let result = match r {
        Ok(b) => ResData{code: 0, msg: "success", data: b},
        Err(e) => {
            error!("添加用户失败:{}", e);
            ResData::fail("fail", ())
        },
    };
    HttpResponse::Ok().json(result) // <- send response
}

/// @Author: DengLibin 榆霖
/// @Date:  2022-07-06 11:17:02
/// @Description: 分页查询
#[get("/get_page")]
async fn get_page(
    mysql_conn_pool: Data<mysql_async::Pool>, //连接池，全局参数传过来
    query: web::Query<HashMap<String, String>>, //查询参数
    ) -> HttpResponse {
    info!("分页查询");
    //获取查询参数
    let page_str = query.get("page").unwrap();
    let size_str = query.get("size").unwrap();
    let page: i32 = page_str.parse().unwrap();
    let size: i32 = size_str.parse().unwrap();
    //获取连接池
    let p = (*(mysql_conn_pool)).clone();
    //查询参数
    let db_param = DbParam {page: page, size: size, pool: p};
    let p = async_user_service::get_page(&db_param).await.unwrap();

    HttpResponse::Ok().json(ResData::success(p)) // <- send response
}



